package cn.woochen.mvvmframe.web

import android.app.Activity
import android.webkit.JavascriptInterface
import cn.woochen.comlib.jsbridge.BaseJavascriptInterface
import cn.woochen.comlib.jsbridge.OnBridgeCallback
import cn.woochen.comlib.jsbridge.WebViewHelper
import cn.woochen.comlib.util.ext.woochenLog

/**
 * Created on 2019/7/10.
 * Author: bigwang
 * Description:
 */
class MainJavascriptInterface(callBacks: MutableMap<String, OnBridgeCallback>?,private val webViewHelper: WebViewHelper) : BaseJavascriptInterface(callBacks) {

    /**
     * 调用js的send方法时，会执行这个方法
     * @param data js传递过来的数据
     * @param responseId 回调id，给js回调数据时，需要使用它构造message对象
     */
    @JavascriptInterface
    override fun send(data: String?,responseId: String?) {
        woochenLog("chromium->${data},responseId：${responseId}")
        runOnUiThread{
            //handle data...
            webViewHelper.response("receive success!",responseId)
        }
    }

    /**
     * 自定义方法，给js调用
     * @param data
     * @param responseId
     */
    @JavascriptInterface
    fun functionInNative(data: String?,responseId: String?) {
        woochenLog("chromium->${data},responseId：${responseId}")
        runOnUiThread {
            //handle data...
            webViewHelper.response("nice,receive success!",responseId)
        }
    }

    private fun runOnUiThread(block:()->Unit){
        if (webViewHelper.context is Activity){
            (webViewHelper.context as Activity).runOnUiThread {
                block.invoke()
            }
        }
    }

}